package com.jandan.ui.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.Connection;
import com.gwtext.client.core.ConnectionConfig;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.HttpProxy;
import com.gwtext.client.data.JsonReader;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.util.JavaScriptObjectHelper;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.PagingToolbar;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import com.gwtext.client.widgets.layout.HorizontalLayout;
import com.jandan.ui.client.service.WordLibService;
import com.jandan.ui.client.service.WordLibServiceAsync;
import com.jandan.ui.model.Word;

public class SearchPanel extends Panel {
	private String url;
	private Button searchButton;
	private ILessonOperator lessonOperator;

	public SearchPanel(ILessonOperator lessonOperator) {
		this.lessonOperator = lessonOperator;
		this.setLayout(new HorizontalLayout(8));
		this.setBorder(true);
		this.setPaddings(60, 20, 0, 0);
		createComponent();
	}

	private void createComponent() {
		url = GWT.getModuleBaseURL() + "/searchword.json?wordLibID=";
		final ConnectionConfig cc = new ConnectionConfig();
		cc.setUrl(url);
		Connection con = new Connection(cc);
		HttpProxy httpProxy = new HttpProxy(con);
		RecordDef recordDef = new RecordDef(new FieldDef[] {
				new StringFieldDef("wordID", "wordID"),
				new StringFieldDef("wordEn", "wordEn"),
				new StringFieldDef("phonetics", "phonetics"),
				new StringFieldDef("wordCn", "wordCn") });

		JsonReader reader = new JsonReader(recordDef);
		reader.setRoot("words");
		reader.setTotalProperty("totalCount");
		reader.setId("wordID");

		final Store store = new Store(httpProxy, reader);
		store.load();

		final String resultTpl = "<div class=\"search-item\"><span class='search-wordEn'>{wordEn}</span><br/><span class=\"phonetics\">{phonetics}</span><br/><span class='search-cn'>{wordCn}</span></div>";

		final ComboBox cb = new ComboBox();
		cb.setStore(store);
		cb.setDisplayField("wordEn");
		cb.setValueField("wordEn");
		cb.setTypeAhead(false);
		cb.setLoadingText("查找中...");
		cb.setWidth(240);
		cb.setEmptyText("请输入要查找的单词");
		cb.setPageSize(10);
		cb.setHideTrigger(true);
		cb.setTpl(resultTpl);
		cb.setMode(ComboBox.REMOTE);
		// cb.setTitle("查找单词");
		cb.setHideLabel(true);
		cb.setItemSelector("div.search-item");
		cb.setQueryParam("word");
		cb.setMinChars(1);

		JavaScriptObjectHelper.setAttribute(cb.getConfig(),"lazyInit", true);
		
		
		cb.addListener(new ComboBoxListenerAdapter() {
			@Override
			public void onSelect(ComboBox comboBox, Record record, int index) {
				// TODO Auto-generated method stub
				Object tbObj = JavaScriptObjectHelper.getAttributeAsObject(cb.getOrCreateJsObj(), "pageTb");
		        // if toolbar was already created 
		        if (tbObj!=null){
		           PagingToolbar tb = new PagingToolbar((JavaScriptObject)tbObj);
		           tb.setPrevText("上一页");
		           tb.setNextText("下一页");
		           tb.setFirstText("第一页");
		           tb.setLastText("最后一页");
		           tb.setAfterPageText("共 {0} 页");
		           tb.setBeforePageText("页");
		           tb.setRefreshText("刷新");
		           tb.setDisplayMsg("显示单词 {0} - {1} 共 {2}");
		           tb.setEmptyMsg("没有此单词");
		        }
				
				String swordID = record.getAsString("wordID");
				if (swordID != null) {
					WordLibServiceAsync wordLibService = WordLibService.Util
							.getInstance();
					long wordID = Long.parseLong(swordID);
					wordLibService.getWordByWordID(wordID,
							new AsyncCallback<Word>() {
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									MessageBox.alert(caught.getMessage());
								}

								public void onSuccess(Word word) {
									// TODO Auto-generated method stub
									if (word == null) {
										MessageBox.alert("没有查到此单词");
										return;
									}
									lessonOperator.displayWordInfo(word);
								}
							});
				}
			}
			
			
		});

		searchButton = new Button("查找");
		searchButton.setId("search");

		searchButton.addListener(new ButtonListenerAdapter() {
			@Override
			public void onClick(Button button, EventObject e) {
				// TODO Auto-generated method stub
				WordLibServiceAsync wordLibService = WordLibService.Util
						.getInstance();
				String wordEn = cb.getValue();

				if (wordEn == null) {
					MessageBox.alert("请输入要查找的单词");
					return ;
				} else if (wordEn.trim().length() <= 0) {
					MessageBox.alert("请输入要查找的单词");
					return;
				}
				wordLibService.getWordByWordEn(wordEn.trim(),
						new AsyncCallback<Word>() {
							public void onFailure(Throwable caught) {
								MessageBox.alert(caught.getMessage());
							}

							public void onSuccess(Word word) {
								if (word == null) {
									return;
								}
								lessonOperator.displayWordInfo(word);
							}
						});
			}
		});

		this.add(cb);
		this.add(searchButton);
	}
}
